package com.muchfish.algorithm.queue;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 232. 用栈实现队列
 * 1.用左右两个栈，入栈时从左栈压入元素，出栈时从右栈弹出元素。
 * 2.弹完了再从左栈先弹，后存入右栈，再从右栈弹
 */
public class MyQueue {
    //维护两个栈
    Deque<Integer> left;//左栈，负责元素入栈
    Deque<Integer> right;//右栈，负责元素出栈

    /**
     * Initialize your data structure here.
     */
    public MyQueue() {
        left = new ArrayDeque();
        right = new ArrayDeque();
    }

    /**
     * Push element x to the back of queue.
     */
    public void push(int x) {
        left.push(x);
    }

    private void reverse() {
        //当右栈为空时,再将左栈内元素全部倒过来，否则会破坏出栈顺序
        if (right.isEmpty()) {
            while (!left.isEmpty()) {
                right.push(left.pop());
            }
        }
    }

    /**
     * Removes the element from in front of queue and returns that element.
     */
    public int pop() {
        reverse();
        return right.pop();
    }

    /**
     * Get the front element.
     */
    public int peek() {
        reverse();
        return right.peek();
    }

    /**
     * Returns whether the queue is empty.
     */
    public boolean empty() {
        return left.isEmpty() && right.isEmpty();
    }
}
